<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import echarts from '@/utils/echarts'
import { cityLineChartService } from '@/apis/home'

// 存储折线图数据
const LineChartData = ref([])

// 获取折线图数据
const getLineChart = async () => {
  const res = await cityLineChartService()
  LineChartData.value = res.data
}
// 获取图表容器
const chartContainerRef = ref(null)

// 声明一个变量用于保存echarts实例
let chartInstance = null

onMounted(async () => {
  // 调用函数获取折线图数据
  await getLineChart()

  if (LineChartData.value.length > 0) {
    // 初始化图表
    chartInstance = echarts.init(chartContainerRef.value)

    // 定义图表的配置项和数据
    const option = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['景点平均价格', '酒店平均价格', '餐厅平均价格']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        axisLabel: {
          interval: 0
        },
        data: LineChartData.value.map((item) => item.city)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '景点平均价格',
          itemStyle: {
            color: 'orange'
          },
          data: LineChartData.value.map((item) => item.sceneryAverage),
          type: 'line',
          smooth: true
        },
        {
          name: '酒店平均价格',
          itemStyle: {
            color: 'red'
          },
          data: LineChartData.value.map((item) => item.hotelAverage),
          type: 'line',
          smooth: true
        },
        {
          name: '餐厅平均价格',
          itemStyle: {
            color: '#64abfd'
          },
          data: LineChartData.value.map((item) => item.restaurantAverage),
          type: 'line',
          smooth: true
        }
      ]
    }

    // 使用配置项和数据显示图表格
    chartInstance.setOption(option)

    // 监听窗口大小变化，自动调整图表大小
    window.addEventListener('resize', () => {
      chartInstance.resize()
    })
  }
})

// 在组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    window.removeEventListener('resize', chartInstance.resize)
  }
})
</script>

<template>
  <div ref="chartContainerRef" class="chart"></div>
</template>

<style lang="scss" scoped>
.chart {
  width: auto;
  height: 300px;
}
</style>
